package com.siruier.boss.ui.dialog

import android.app.Dialog
import android.content.Context
import android.graphics.drawable.GradientDrawable
import android.view.Gravity
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.core.view.ViewCompat
import androidx.core.view.isVisible
import androidx.recyclerview.widget.DefaultItemAnimator
import androidx.recyclerview.widget.DividerItemDecoration
import com.google.android.flexbox.AlignItems
import com.google.android.flexbox.FlexDirection
import com.google.android.flexbox.FlexWrap
import com.siruier.boss.R
import com.siruier.boss.bean.MallGoodsProductBean
import com.siruier.boss.bean.MallGoodsSpecChildrenBean
import com.siruier.boss.bean.MallGoodsSpecInfoBean
import com.siruier.boss.bean.MallGoodsSpecReceiveBean
import com.siruier.boss.common.formatPrice
import com.siruier.boss.databinding.DialogProductSpecBinding
import com.siruier.boss.databinding.ItemGoodsFirstSpecBinding
import com.siruier.boss.databinding.ItemGoodsSpecBinding
import com.siruier.boss.ui.base.BaseRecyclerAdapter
import com.siruier.boss.ui.base.BaseSignCheckAdapter
import com.siruier.boss.ui.ext.dp
import com.siruier.boss.ui.ext.getString
import com.siruier.boss.ui.ext.toColor
import com.siruier.boss.ui.ext.toastMessageLong
import com.siruier.boss.ui.utils.FullyFlexboxLayoutManager
import com.siruier.boss.ui.utils.FullyLinearLayoutManager
import com.siruier.boss.ui.utils.GlideUtils

class ProductSpecDialog(
    context: Context,
    goodsName: String?,
    type: Int?,
    private val mallGoodsSpecInfoBean: MallGoodsSpecInfoBean,
    buttonBuyNowListener: ((goodsSpecBean: MallGoodsProductBean, number: Int) -> Unit)? = null
) : Dialog(context, R.style.bottomDimLoadingdialog) {
    private val mProductSpecAdapter: ProductFirstSpecAdapter = ProductFirstSpecAdapter()
    private val mAllChildrenSpec = mutableListOf<MallGoodsSpecChildrenBean>()// 所有的子规格
    private var mMallGoodsProductBean: MallGoodsProductBean? = null// 当前选中具体规格参数
    private val vb: DialogProductSpecBinding = DialogProductSpecBinding.inflate(LayoutInflater.from(context))

    init {
        setContentView(vb.root)
        mallGoodsSpecInfoBean.specnList.forEach {
            it.values.forEachIndexed { index, mallGoodsSpecChildrenBean ->
                if (0 == index) {
                    mallGoodsSpecChildrenBean.check = true
                }
                mAllChildrenSpec.add(mallGoodsSpecChildrenBean)
            }
        }
        vb.tvGoodsName.text = goodsName ?: ""
        changeSpec()
        vb.narv.minNumber = 1
        vb.narv.number = 1
        vb.groupSpecNumber.isVisible = type != 4
        mProductSpecAdapter.datas = mallGoodsSpecInfoBean.specnList
        mProductSpecAdapter.setOnClickAdapterListenter(::onClickAdapter)
        vb.rvSpec.adapter = mProductSpecAdapter
        vb.rvSpec.layoutManager = FullyLinearLayoutManager(context)
        vb.rvSpec.addItemDecoration(DividerItemDecoration(context, DividerItemDecoration.VERTICAL))
        vb.buttonBuyNow.setOnClickListener {
            buttonBuyNowListener?.let {
                if (mMallGoodsProductBean == null) {
                    "请先选择规格".toastMessageLong()
                    return@let
                }
                if (vb.narv.number > mMallGoodsProductBean!!.number) {
                    "不能超过库存".toastMessageLong()
                    return@let
                }
                if (vb.narv.number < 1) {
                    "最少购买一件".toastMessageLong()
                    return@let
                }
                it.invoke(mMallGoodsProductBean!!, vb.narv.number)
                dismiss()
            }
        }
        vb.ivClose.setOnClickListener { dismiss() }
        window?.let {
            val attributes = it.attributes
            attributes.width = getContext().resources.displayMetrics.widthPixels
            attributes.height = ViewGroup.LayoutParams.WRAP_CONTENT
            it.attributes = attributes
            it.setGravity(Gravity.BOTTOM)
        }
    }

    private fun onClickAdapter(view: View, position: Int) {
        changeSpec()
    }

    private fun changeSpec() {
        val mMallGoodsSpecChildrenBean = mAllChildrenSpec.find { it.check }
        mallGoodsSpecInfoBean.goodsProductMap["${mMallGoodsSpecChildrenBean?.id}"]
            ?.apply {
                mMallGoodsProductBean = this
                GlideUtils.intoRoundedCorners(context, url, vb.ivSpecImage, roundingRadius = 5)
                vb.tvMemberPrice.text = priceDesc
                vb.tvStock.text = context.getString(R.string.text_shop_mall_reserve, number.toString())
                vb.tvSelectSpace.text = "已选择${mMallGoodsSpecChildrenBean?.value}"
            }
    }
}

class ProductFirstSpecAdapter : BaseRecyclerAdapter<ItemGoodsFirstSpecBinding, MallGoodsSpecReceiveBean>() {
    override fun onBindViewHolder(vb: ItemGoodsFirstSpecBinding, bean: MallGoodsSpecReceiveBean, position: Int) {
        vb.run {
            bean.run {
                tvFirstName.text = name
                // 规格一次加载完不优化
                rvChildrenSpec.adapter = ProductSpecAdapter().apply {
                    datas = values
                    setOnClickAdapterListenter { view, i ->
                        this@ProductFirstSpecAdapter.invokeOnClickAdapterListenter(view, i)
                    }// 此处view，i没有意义，主要是为了触发外部点击回调
                }
                rvChildrenSpec.layoutManager = FullyFlexboxLayoutManager(rvChildrenSpec.context).apply {
                    flexDirection = FlexDirection.ROW; flexWrap = FlexWrap.WRAP;alignItems = AlignItems.STRETCH
                }
                (rvChildrenSpec.itemAnimator as DefaultItemAnimator).supportsChangeAnimations = false
            }
        }
    }

}

class ProductSpecAdapter : BaseSignCheckAdapter<ItemGoodsSpecBinding, MallGoodsSpecChildrenBean>() {

    override fun onBindViewHolder(vb: ItemGoodsSpecBinding, bean: MallGoodsSpecChildrenBean, position: Int) {
        vb.run {
            bean.run {
                tvSpec.text = value
                val radius = 15.dp.toFloat()
                if (check) {
                    ViewCompat.setBackground(tvSpec, GradientDrawable().apply {
                        cornerRadius = radius
                        setColor(R.color.goods_spec_check_bg.toColor())
                        setStroke(1.dp, R.color.goods_spec_check_text.toColor())
                    })
                    tvSpec.setTextColor(R.color.goods_spec_check_text.toColor())
                } else {
                    ViewCompat.setBackground(tvSpec, GradientDrawable().apply {
                        cornerRadius = radius
                        setColor(R.color.bg.toColor())
                    })
                    tvSpec.setTextColor(R.color.text_color.toColor())
                }
                setViewClick(position, root)
            }
        }
    }

}